package cc.linker.steplink.crm.merchant.controller.acs;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.pojo.AccountSummaryPo;
import cc.linker.steplink.crm.merchant.pojo.BindBankInfoPo;
import cc.linker.steplink.crm.merchant.pojo.TransactionDetailsPo;
import cc.linker.steplink.crm.merchant.service.acs.XbMerchantService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 联盟商家
 * @Author: 锋
 * @Date: 2019/9/23 19:29
 * @Version: 1.9.1
 */
@RestController
@RequestMapping("/acs/xbMerchant")
public class XbMerchantController {

    @Autowired
    private XbMerchantService xbMerchantService;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 获取账户概况
     *
     * @return
     */
    @GetMapping("/getAccountInfo")
    public Map<String, Object> getWallet(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        Map<String, Object> record = xbMerchantService.getAccountInfo(adminId, orgId);
        if (record != null && record.get("customerBalance") != null) {
            Long customerBalance = (Long) record.get("customerBalance");
            //Long customerFreeze = (Long) record.get("customerFreeze");
            Long customerFreeze = 0l;
            Long customerTotalBalance = customerBalance + customerFreeze;
            String userId = userinfo.getAdminId();
            Map<String, Object> customerInfo = xbMerchantService.getShopInfo(userId);
            Map<String, Object> params = new HashMap<>();
            if (customerInfo != null && customerInfo.get("customerId") != null) {
                //小B
                params.put("tradeType",-1);
                params.put("customerId", customerInfo.get("customerId").toString());
                params.put("customerType", 1);
            }  else {
                //大B
                params.put("tradeType",-1);
                params.put("customerId", orgId);
                params.put("customerType", 2);
            }
            customerFreeze = xbMerchantService.getCustomerFreeze(params);
            record.put("customerTotalBalance", NumberUtils.fenToYuan(customerTotalBalance));
            record.put("customerBalance", NumberUtils.fenToYuan(customerBalance));
            record.put("customerFreeze", NumberUtils.fenToYuan(customerFreeze));
        } else {
            record = new HashMap<>(3);
            record.put("customerTotalBalance", 0);
            record.put("customerBalance", 0);
            record.put("customerFreeze", 0);
        }
        record.remove("accoutId");
        return record;
    }

    /**
     * @Description: 银行卡绑定
     * @Param:
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/19 14:50
     * @Version: 1.9.1
     */
    @PostMapping("/bankCardBind")
    public void bankCardBind(HttpServletRequest request, @RequestBody Map<String, String> map) throws Exception {
        if (!map.containsKey("bankId") || !map.containsKey("bankAccountNumber")) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        String payMode = userinfo.getPayMode().toString();
        map.put("adminId", adminId);
        map.put("orgId", orgId);
        map.put("payMode", payMode);
        xbMerchantService.bankCardBind(map);
    }

    /**
     * @Description: 银行卡换绑
     * @Param:
     * @Return:
     * @Author: ch
     * @Date: 2021/1/12 19:50
     * @Version: 1.12.19
     */
    @PostMapping("/bankCardChange")
    public void bankCardChange(HttpServletRequest request, @RequestBody Map<String, String> map) throws Exception {
        if (!map.containsKey("bankId") || !map.containsKey("bankAccountNumber")) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        String payMode = userinfo.getPayMode().toString();
        map.put("adminId", adminId);
        map.put("orgId", orgId);
        map.put("payMode", payMode);
        xbMerchantService.bankCardChange(map);
    }

    /**
     * @Description: 获取绑定银行卡信息
     * @Param:
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/19 14:50
     * @Version: 1.9.1
     */
    @GetMapping("/getBindBankInfo")
    public BindBankInfoPo getBindBankInfo(HttpServletRequest request,
                                          @RequestParam(value = "customerId", required = false) String customerId) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, String> map = new HashMap<>();
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        map.put("adminId", adminId);
        map.put("orgId", orgId);
        map.put("customerId", customerId);
        return xbMerchantService.getBindBankInfo(map);
    }

    /**
     * @Description: 提现
     * @Param:
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/19 14:50
     * @Version: 1.9.1
     */
    @PostMapping("/withdraw")
    public void withdraw(HttpServletRequest request,
                         @RequestBody Map<String, Object> map) throws Exception {
        if (!map.containsKey("withdrawAmount")) {
            throw GlobalException.build("请填写提现金额");
        }
        if (Float.valueOf(map.get("withdrawAmount").toString()) == 0) {
            throw GlobalException.build("提现金额必须大于0元");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        map.put("adminId", adminId);
        map.put("orgId", orgId);
        xbMerchantService.withdraw(map);
    }

    @GetMapping("/checkwithdraw")
    public Map checkWithDraw(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        Boolean ifSales = userinfo.getSaler();
        Map<String, Object> param = new HashMap<>();
        param.put("adminId", adminId);
        param.put("orgId", orgId);
        param.put("customerType", "12");
        param.put("ifSales", ifSales);
        Integer count = xbMerchantService.checkWithDraw(param);
        Map<String, Object> res = new HashMap<>();
        res.put("count", count > 0 ? 1 : 0);
        return res;
    }

    /**
     * @Description: 打款校验
     * @Param:
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/19 14:50
     * @Version: 1.9.1
     */
    @PostMapping("/checkBankSendMoney")
    public void checkBankSendMoney(HttpServletRequest request,
                                   @RequestBody Map<String, Object> map) throws Exception {
        if (!map.containsKey("sendMoney")) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        map.put("adminId", adminId);
        map.put("orgId", orgId);
        xbMerchantService.checkBankSendMoney(map);
    }


    /**
     * @Description: 获取交易记录
     * @Param:
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/20 16:57
     * @Version: 1.9.1
     */
    @GetMapping("/getTransactionDetails")
    public PageInfo<TransactionDetailsPo> getTransactionDetails(@RequestParam(defaultValue = "20") Integer pageSize,
                                                                @RequestParam(defaultValue = "1") Integer pageIndex,
                                                                String startTime, String endTime, String keywords,
                                                                String tradeOrder, Integer tradeType,
                                                                HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        params.put("perPage", pageSize);
        params.put("pageIndex", pageIndex);
        if (StringUtil.isNotEmpty(startTime)) {
            params.put("startTime", startTime + " 00:00:00");
            params.put("endTime", endTime + " 23:59:59");
        }
        params.put("tradeOrder", tradeOrder);
        params.put("tradeType", tradeType);
        params.put("keywords", keywords);
        params.put("orgId", userinfo.getOrgId());

        String userId = userinfo.getAdminId();
        Map<String, Object> customerInfo = xbMerchantService.getShopInfo(userId);
        String dongCustomerId = xbMerchantService.getDongCustomerIdByUserId(userId);
        if (customerInfo != null && customerInfo.get("customerId") != null) {
            //小B
            params.put("salerId", customerInfo.get("customerId").toString());
            params.put("customerType", 1);
        } else if (!StringUtils.isEmpty(dongCustomerId)) {
            params.put("salerId", dongCustomerId);
            params.put("customerType", 1);
        } else {
            //大B
            params.put("salerId", params.get("orgId"));
            params.put("customerType", 2);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(xbMerchantService.getTransactionDetails(params));
    }

    @GetMapping("/exportTransactionDetails")
    public void exportTransactionDetails(
        String startTime, String endTime, String keywords,String tradeOrder, Integer tradeType,HttpServletRequest request,HttpServletResponse response
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        if (StringUtil.isNotEmpty(startTime)) {
            params.put("startTime", startTime + " 00:00:00");
            params.put("endTime", endTime + " 23:59:59");
        }
        params.put("tradeOrder", tradeOrder);
        params.put("tradeType", tradeType);
        params.put("keywords", keywords);
        params.put("orgId", userinfo.getOrgId());

        String userId = userinfo.getAdminId();
        Map<String, Object> customerInfo = xbMerchantService.getShopInfo(userId);
        String dongCustomerId = xbMerchantService.getDongCustomerIdByUserId(userId);
        if (customerInfo != null && customerInfo.get("customerId") != null) {
            //小B
            params.put("salerId", customerInfo.get("customerId").toString());
            params.put("customerType", 1);
        } else if (!StringUtils.isEmpty(dongCustomerId)) {
            params.put("salerId", dongCustomerId);
            params.put("customerType", 1);
        } else {
            //大B
            params.put("salerId", params.get("orgId"));
            params.put("customerType", 2);
        }
        xbMerchantService.exportTransactionDetails(params,response);
    }

    /**
     * @Description: 获取对账单
     * @Param:
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/20 16:57
     * @Version: 1.9.1
     */
    @GetMapping("/getAccountSummary")
    public PageInfo<AccountSummaryPo> getAccountSummary(@RequestParam(defaultValue = "20") Integer pageSize,
                                                        @RequestParam(defaultValue = "1") Integer pageIndex,
                                                        @RequestParam(defaultValue = "month") String scale,
                                                        String statisticalTime, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isEmpty(statisticalTime)) {
            throw GlobalException.build("缺少参数");
        }
        if ("month".equals(scale)) {
            statisticalTime += "-01";
        } else if ("year".equals(scale)) {
            int month = 1;
            int year = LocalDateTime.now().getYear();
            if (Integer.valueOf(statisticalTime) < year) {
                // 查往年账单
                params.put("previous", 1);
            } else {
                // 查今年账单
                month = LocalDateTime.now().getMonth().getValue();
            }
            statisticalTime += ("-" + month + "-01");
        } else {
            throw GlobalException.build("格式错误");
        }

        params.put("perPage", pageSize);
        params.put("pageIndex", pageIndex);
        params.put("statisticalTime", statisticalTime);
        params.put("scale", scale);
        params.put("orgId", userinfo.getOrgId());

        String userId = userinfo.getAdminId();
        Map<String, Object> customerInfo = xbMerchantService.getShopInfo(userId);
        if (customerInfo != null && customerInfo.get("customerId") != null) {
            //小B
            params.put("salerId", customerInfo.get("customerId").toString());
            params.put("customerType", 1);
        } else {
            //大B
            params.put("salerId", params.get("orgId"));
            params.put("customerType", 2);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(xbMerchantService.getAccountSummary(params));
    }

    /**
     * 对账单详情
     *
     * @param : date 日期如果为月则2019-10，如果为日则2019-10-22
     */
    @PostMapping("/getAccountDetail")
    public Map<String, Object> getAccountDetail(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean ifSales = userinfo.getSaler();
        map.put("sales", ifSales);
        String orgId = userinfo.getOrgId();
        map.put("orgId", orgId);
        String adminId = userinfo.getAdminId();
        map.put("adminId", adminId);
        return xbMerchantService.getAccountDetail(map);
    }

    /**
     * 对账单导出excel
     *
     * @param date 同上
     */
    @GetMapping("/downloadAccountDetail")
    public void downloadAccountDetail(String date, HttpServletRequest request, HttpServletResponse response) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> map = new HashMap<>();
        map.put("date", date);
        Boolean ifSales = userinfo.getSaler();
        map.put("sales", ifSales);
        String orgId = userinfo.getOrgId();
        map.put("orgId", orgId);
        String adminId = userinfo.getAdminId();
        map.put("adminId", adminId);
        xbMerchantService.downloadAccountDetail(map, response);
    }

    /**
     * 引导页参数
     */
    @GetMapping("/guide")
    public Map<String, Object> guide(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean ifSales = userinfo.getSaler();
        if (!ifSales) {
            throw GlobalException.build("角色错误");
        }
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        Map<String, Object> map = new HashMap<>();
        map.put("adminId", adminId);
        map.put("orgId", orgId);
        return xbMerchantService.getGuideInfo(map);
    }


    /**
     * 不再显示引导页
     *
     * @param display 0-不显示1-显示
     */
    @GetMapping("/displayGuide")
    public void displayGuide(String display, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean ifSales = userinfo.getSaler();
        if (!ifSales) {
            throw GlobalException.build("角色错误");
        }
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        Map<String, Object> map = new HashMap<>();
        map.put("adminId", adminId);
        map.put("orgId", orgId);
        map.put("display", display);
        xbMerchantService.displayGuide(map);
    }


    /**
     * 交易明细列表
     * @return
     */
    @GetMapping("/tradelist")
    public PageInfo<Map<String,Object>> tradeList(
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer pageIndex,
            String startTime, String endTime,
            String orderSn, Integer tradeType,
            HttpServletRequest request
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("orderSn",orderSn);
        if(!StringUtils.isEmpty(orderSn) && orderSn.startsWith("wq")){
            String wqSn = orderSn.substring(2,orderSn.length()-5);
            params.put("orderSn",wqSn);
        }
        params.put("tradeType",tradeType);
        params.put("orgId", userinfo.getOrgId());
        params.put("pageIndex", pageIndex);
        params.put("pageSize", pageSize);

        String userId = userinfo.getAdminId();
        Map<String, Object> customerInfo = xbMerchantService.getShopInfo(userId);
        if (customerInfo != null && customerInfo.get("customerId") != null) {
            //小B
            params.put("customerId", customerInfo.get("customerId").toString());
            params.put("customerType", 1);
        }  else {
            //大B
            params.put("customerId", params.get("orgId"));
            params.put("customerType", 2);
        }
        return xbMerchantService.tradeList(params);
    }


    /**
     * 交易明细列表
     * @return
     */
    @GetMapping("/exportTradelist")
    public void exportTradelist(
            String startTime, String endTime,
            String orderSn, Integer tradeType,
            HttpServletRequest request, HttpServletResponse response
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("orderSn",orderSn);
        if(!StringUtils.isEmpty(orderSn) && orderSn.startsWith("wq")){
            String wqSn = orderSn.substring(2,orderSn.length()-5);
            params.put("orderSn",wqSn);
        }
        params.put("tradeType",tradeType);
        params.put("orgId", userinfo.getOrgId());
        String userId = userinfo.getAdminId();
        Map<String, Object> customerInfo = xbMerchantService.getShopInfo(userId);
        if (customerInfo != null && customerInfo.get("customerId") != null) {
            //小B
            params.put("customerId", customerInfo.get("customerId").toString());
            params.put("customerType", 1);
        }  else {
            //大B
            params.put("customerId", params.get("orgId"));
            params.put("customerType", 2);
        }
        xbMerchantService.exportTradelist(params,response);
    }

    @GetMapping("/getShopName")
    public String getShopName(String customerId){
        Map<String,Object> map = new HashMap<>();
        map.put("customerId", customerId);
        return xbMerchantService.getShopName(map);
    }

    @GetMapping("/getShopNameAndLogo")
    public String getShopNameAndLogo(String customerId){
        Map<String,Object> map = new HashMap<>();
        map.put("customerId", customerId);
        return xbMerchantService.getShopNameAndLogo(map);
    }

}
